package com.shenghui.enterprise.base.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.shenghui.enterprise.base.entity.BaseUser;
import com.shenghui.enterprise.utils.GeneralUtil;
import com.shenghui.enterprise.utils.MD5;
import com.shenghui.enterprise.utils.UserUtil;
import com.shenghui.enterprise.vo.Result;
import com.shenghui.enterprise.base.mapper.BaseUserMapper;
import com.shenghui.enterprise.base.service.ILoginService;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.time.LocalDateTime;
import java.util.Map;

/**
 * @Description: 登录服务接口实现类
 * @Author houjh
 * @Email: happyxiaohou@gmail.com
 * @Date: 2020-05-29
 * @Copyright (c) 2020-2022 云南昇晖科技有限公司
 */
@Service
public class LoginServiceImpl extends ServiceImpl<BaseUserMapper, BaseUser> implements ILoginService {

    @Resource
    private BaseUserMapper userMapper;
    @Resource
    private UserUtil userUtil;

    @Override
    public Object login(Map map, HttpServletRequest request, HttpServletResponse response) {
        String account = map.get("account").toString().trim();
        String password = map.get("password").toString().trim();
        BaseUser baseUser = userMapper.selectOne(new QueryWrapper<BaseUser>().lambda()
                .eq(BaseUser::getAccount, account)
                .eq(BaseUser::getPassword, MD5.MD5Encode(password))
        );
        if (GeneralUtil.isNull(baseUser)) {
            return Result.error( "登录账号或密码不存在");
        }
        userUtil.setLoginUser(request, baseUser);
        // 修改登录时间
        baseUser.setLastLoginTime(LocalDateTime.now());
        userMapper.updateById(baseUser);
        return Result.ok("登录成功");
    }

    @Override
    public Object loginOut(HttpServletRequest request) {
        userUtil.logout(request);
        return Result.ok( "退出成功");
    }

}
